package top.sdaily.web.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.sdaily.core.mybatis.Conditions;
import top.sdaily.core.utils.IdGeneratorUtils;
import top.sdaily.mapper.DictMapper;
import top.sdaily.web.exception.FailedException;
import top.sdaily.web.model.Dict;
import top.sdaily.web.service.DictService;

import java.util.List;

/**
 * Created by tsujishiki on 2017/1/24.
 */
@Service
@Transactional
public class DictServiceImpl implements DictService {

    @Autowired
    DictMapper dictMapper;

    @Override
    public List<Dict> getAll() {
        return dictMapper.findList(new Conditions(Dict.class).eq("parent_id",0));
    }

    @Override
    public void create(Dict dict) {
        notExists(dict);
        dict.setPkid(IdGeneratorUtils.fresh());
        dictMapper.insert(dict);
    }

    @Override
    public void modify(Dict dict) {
        notExists(dict);
        dictMapper.update(dict);
    }

    @Override
    public void delete(String pkid) {
        dictMapper.delete(new Conditions(Dict.class).id(pkid));
        dictMapper.delete(new Conditions(Dict.class).eq("parent_id",pkid));
    }

    @Override
    public List<Dict> getByParent(String pkid) {
        return dictMapper.findList(new Conditions(Dict.class).eq("parent_id",pkid));
    }

    private void notExists(Dict dict){
        if("0".equals(dict.getParentId())){
            Conditions conditions = new Conditions(Dict.class)
                    .eq("parent_id",dict.getParentId())
                    .eq("name",dict.getName());
            if(dict.getPkid() != null)
                conditions.neq("pkid",dict.getPkid());

            Dict one = dictMapper.findOne(conditions);
            if(one != null) throw new FailedException("该字典已存在");
        } else {
            Conditions conditions = new Conditions(Dict.class)
                    .eq("parent_id", dict.getParentId())
                    .eq("value",dict.getValue());
            if(dict.getPkid() != null)
                conditions.neq("pkid",dict.getPkid());

            Dict one = dictMapper.findOne(conditions);
            if(one != null) throw new FailedException("该字典已存在");
        }
    }

}
